package l1j.server.GameServer;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

import l1j.server.echo.ClientThread;


/**
 * IP攻擊行為檢查器
 * @author loli
 */
public class IpAttackCheck {

	private class IpTemp {
		long _time;
		int _count;
	}

	private static final Logger _log = Logger.getLogger(IpAttackCheck.class.getName());

	public static final Map<ClientThread, String> SOCKETLIST = new ConcurrentHashMap<ClientThread, String>();// DaiEn 2012-04-25

	private static final HashMap<String, IpTemp> _ipList = new HashMap<String, IpTemp>();

	private static IpAttackCheck _instance;

	public static IpAttackCheck get() {
		if (_instance == null) {
			_instance = new IpAttackCheck();
		}
		return _instance;
	}

	private IpAttackCheck() {
		_ipList.clear();
	}

	public boolean check(String key) {
		try{
			final long time = System.currentTimeMillis();
			IpTemp value = _ipList.get(key);

			if (value == null) {
				value = new IpTemp();
				value._time = time;
				value._count = 1;
				_ipList.put(key, value);

			} else {
				if (time - value._time <= 15000) {
					value._count += 1;
				}
				value._time = time;
				if (value._count >= 10) {
					this.kick(key);
					/*if (ConfigIpCheck.SETDB) { // 判斷IP是否寫入資料庫
						// 加入IP封鎖
						IpReading.get().add(key, "IP類似攻擊行為");
						return false;
					}*/
				}
			}

		} catch(final Exception e){
			_log.log(Level.SEVERE ,e.getLocalizedMessage(), e);
		}
		return true;
	}

	// 中斷相同IP所有連線 DaiEn 2012-04-25
	private void kick(final String key) {
		try{
			for (final ClientThread socket : SOCKETLIST.keySet()) {
				final String ip = SOCKETLIST.get(socket);
				if (ip != null) {
					if (ip.equals(key)) {
						socket.close();
						_log.info("中斷相同IP所有連線。");
					}
				}
			}
		} catch(final Exception e){
			_log.log(Level.SEVERE ,e.getLocalizedMessage(), e);
		}
	}
}
